package com.gimi.cloud.jimi.common.utils;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.reqhead.Verification;

import java.util.Set;

/**
 * Created by luck on 2017/10/13.
 */
public class EntityVerification {


    public static <T>  void checkEntityThrowsException(T obj) throws MsgException {
        StringBuffer stringBuffer = new StringBuffer();
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> constraintViolation = validator.validate(obj);
        for (ConstraintViolation<T> ut : constraintViolation) {
            stringBuffer.append(ut.getPropertyPath());
            stringBuffer.append(":");
            stringBuffer.append(ut.getMessage());
            stringBuffer.append(",");
        }
        String msg = stringBuffer.toString();
        if (!StringUtil.isEmpty(msg)) {
        	msg = msg.substring(0, msg.length()-1);
        	throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR, "{" + msg + "}");
        }
        
    }
    
    public static <T> Verification checkEntity(T obj) throws MsgException {
        StringBuffer stringBuffer = new StringBuffer();
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> constraintViolation = validator.validate(obj);
        for (ConstraintViolation<T> ut : constraintViolation) {
            stringBuffer.append(ut.getPropertyPath());
            stringBuffer.append(":");
            stringBuffer.append(ut.getMessage());
            stringBuffer.append(",");
        }
        String msg = stringBuffer.toString();
        if (!StringUtil.isEmpty(msg)) {
        	msg = msg.substring(0, msg.length()-1);
        	return new Verification(false, msg);
        }
		return new Verification(true, null);
        
    }

    public static <T>  void checkByGroupsThrowsException(T obj,Class... group) throws MsgException {
        StringBuffer stringBuffer = new StringBuffer();
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> constraintViolation = validator.validate(obj,group);
        for (ConstraintViolation<T> ut : constraintViolation) {
            stringBuffer.append(ut.getPropertyPath());
            stringBuffer.append(":");
            stringBuffer.append(ut.getMessage());
            stringBuffer.append(",");
        }
        String msg = stringBuffer.toString();
        if (!StringUtil.isEmpty(msg)) {
            msg = msg.substring(0, msg.length()-1);
            throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR, "{" + msg + "}");
        }

    }

}
